﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace LCARSLibrary
{
    public static class SerializationHelper
    {  
        public static void SerializeXML(object data, Type type, string file)
        {
            // serialisieren 
            XmlSerializer serializer = new XmlSerializer(type);
            FileStream fs = new FileStream(file, FileMode.Create);
            serializer.Serialize(fs, data);
            fs.Close();
        }

        public static object DeserializeXML(Type type, string file)
        {
            object result = null;

            try
            {

                if (File.Exists(file))
                {
                    // deserialisieren 
                    XmlSerializer serializer = new XmlSerializer(type);
                    FileStream fs = new FileStream(file, FileMode.Open);
                    result = serializer.Deserialize(fs);
                    fs.Close();
                }
                else
                {
                    result = null;
                }
            }
            catch
            {
                return null;
            }

            return result;
        }

        public static object DeserializeBinary(string file)
        {
            object result = null;

            try
            {
                if (File.Exists(file))
                {
                    // Deserialization
                    BinaryFormatter binFormatter = new BinaryFormatter();
                    FileStream fileStream = new FileStream(file, FileMode.Open);
                    result = binFormatter.Deserialize(fileStream);
                    fileStream.Close();
                }
                else
                {
                    result = null;
                }
            }
            catch
            {
                return null;
            }

            return result;
        }

        public static void SerializeBinary(object data, string file)
        {
            //Serialization
            BinaryFormatter binFormatter = new BinaryFormatter();
            FileStream fileStream = new FileStream(file, FileMode.Create);
            binFormatter.Serialize(fileStream, data);
            fileStream.Close();
        }
    }
}
